package com.example.socket;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/download")
public class DownloadPic {
    private static final String sourceFolder = "C:\\project\\dataset\\重新分类"; // 本地图片文件夹路径
    //    private static final String sourceFolder = "G:\\JavaProJectLocal\\卷包\\芜湖图片"; // 本地图片文件夹路径
    @RequestMapping("/{imageName}")
    public void previewImage(@PathVariable String imageName, HttpServletResponse response) throws IOException {
        String filePath = sourceFolder + "\\" + imageName;
        File file = new File(filePath);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("File not found");
            return;
        }

        // 根据文件扩展名设置正确的 Content-Type
        String contentType = Files.probeContentType(file.toPath());
        if (contentType == null) {
            contentType = "application/octet-stream"; // fallback 类型
        }

        response.setContentType(contentType);
        response.setCharacterEncoding("UTF-8");

        try (
                OutputStream out = response.getOutputStream();
                BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file))
        ) {
            byte[] content = new byte[10240];
            int length;
            while ((length = fin.read(content)) != -1) {
                out.write(content, 0, length);
            }
            out.flush();
        }
    }
}
